import React, { useState } from "react";
import "./App.css";
import "fontsource-roboto";
import { Container, Dialog, Grid, makeStyles, Theme } from "@material-ui/core";
import SpeedDials from "./SpeedDials";
import SimpleUploadDialog from "./SimpleUploadDialog";
import CircularProgress from "@material-ui/core/CircularProgress";
import { Alert } from "@material-ui/lab";
import { I18nItem } from "./types";
import ItemCard from "./ItemCard";
import { saveAs } from "file-saver";

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    minHeight: "100vh",
    paddingTop: theme.spacing(4),
  },
  process: {
    "& .MuiDialog-paper": {
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      width: 64,
      height: 64,
      // background: "transparent",
    },
  },
  grid: {
    flexGrow: 1,
  },
}));

const readFile = (file: File) => {
  return new Promise((resolve) => {
    const fileReader = new FileReader();
    fileReader.onload = () => {
      resolve(JSON.parse(fileReader.result as string));
    };
    fileReader.readAsText(file, "utf-8");
  });
};

const saveFile = (data: string, filename: string) => {
  const blob = new Blob([data], { type: "text/plain;charset=utf-8" });
  saveAs(blob, filename);
};

function App() {
  const classes = useStyles();
  const [open, setOpen] = React.useState(false);
  const [processOpen, setProcessOpen] = React.useState(false);
  const [content, setContent] = useState<Record<string, I18nItem> | null>(null);
  const [contentLoaded, setContentLoaded] = useState(false);

  const handleUploadDialogClose = async (file?: File) => {
    setOpen(false);

    if (file) {
      // setProcessOpen(true);
      const result = (await readFile(file)) as Record<string, I18nItem>;
      if (content) {
        const newContent: Record<string, I18nItem> = {};
        Object.entries(content).forEach(([key, value]) => {
          const newItem = result[key];
          console.log("newItem ---> ", newItem);
          newContent[key] = newItem
            ? {
                ...value,
                translated: !!newItem.translated,
                defaultMessage: newItem.defaultMessage,
              }
            : value;
        });
        console.log(newContent)
        setContent(newContent);
      } else {
        setContent(result as Record<string, I18nItem>);
        setContentLoaded(true);
      }
      setProcessOpen(false);
    }
  };

  const handleAction = (action: string) => {
    if (action === "Add") {
      setOpen(true);
      return;
    }

    if (action === "Save") {
      saveFile(JSON.stringify(content, null, 2), "messages.json");
    }
  };

  const updateItem = (id: string, item: I18nItem) => {
    setContent({
      ...content,
      [id]: item,
    });
  };

  return (
    <Container className={classes.root}>
      {contentLoaded && <Alert severity="success">基础配置已上传。</Alert>}
      <Grid container className={classes.root} spacing={2}>
        {contentLoaded &&
          Object.entries(content as Record<string, I18nItem>).map(
            ([key, value]) => {
              return (
                <Grid key={key} item xs={12}>
                  <ItemCard id={key} item={value} updateItem={updateItem} />
                </Grid>
              );
            }
          )}
      </Grid>
      <SpeedDials handleAction={handleAction} />
      <Dialog
        className={classes.process}
        aria-labelledby="process"
        open={processOpen}
      >
        <CircularProgress />
      </Dialog>
      <SimpleUploadDialog open={open} onClose={handleUploadDialogClose} />
    </Container>
  );
}

export default App;
